/* global Vue */
import styles from '../css/index.scss'
import 'nprogress/nprogress.css'

import { decorate } from 'common/axio-decorate'
import global from 'common/globals'
import ElSearch from 'components/search'
import LayoutTopMenu from 'components/layout-top-menu'
import NoRecord from 'components/no-record'
import hasPermission from 'mixins/permission'
import * as filters from 'filters/form'
import router from './router'
import { setInitialStates } from './store/state'
import { getMenuListAndPermision } from './app/models'
import { getStore } from './store'
import App from './app'

const { appPrefix } = styles

function bootVueInstance(store) {
  Object.keys(filters).forEach((key) => {
    Vue.filter(key, filters[key])
  })

  Vue.mixin(hasPermission);
  Vue.component('ElSearch', ElSearch)
  Vue.component('LayoutTopMenu', LayoutTopMenu)
  Vue.component('NoRecord', NoRecord)

  new Vue({
    router,
    store,
    render: (h) => {
      global.store = store
      return h(App)
    }
  }).$mount('#app')
}

function bootStrap() {
  const state = setInitialStates({ appPrefix })
  let store = null
  decorate()
  getMenuListAndPermision().then(res => {
    store = getStore(state)
    Vue.prototype.$globalStore = store

    state.leftMenu.menuList = res['menuList']
    state.user.permissionList = res['permissions']
    state.user.isAdmin = res['isAdmin']
    bootVueInstance(store)
  }).catch(err => {
    console.error('bootStrap err:', err)
    window.location.href = 'login.html'
  })
}

bootStrap()
